Converting objects into strings
Let's first make a variable called obj, setting it equal to an object. On this object, we'll just define one
property, name, and set it equal to your first name; I'll set this one equal to Andrew, as shown here:
var obj = { name: 'Andrew'
};
Now, let's assume that we want to take this object and work on it. Let's say we want to, for example, send
it between servers as a string and save it to a text file. To do this, we'll need to call one JSON method.
Let's take a moment to define a variable to store the result, stringObj, and we'll set it equal to
JSON.stringify, as shown here:
var stringObj = JSON.stringify(obj);
The JSON.stringify method takes your object, in this case, the obj variable, and returns the JSON-stringified
version. This means that the result stored in stringObj is actually a string. It's no longer an object, and we
can take a look at that using console.log. I'll use console.log twice. First up, we'll use the typeof operator to
print the type of the string object to make sure that it actually is a string. Since typeof is an operator, it gets
typed in lowercase, there is no camel casing. Then, you pass in the variable whose type you want to check.
Next up, we can use console.log to print the contents of the string itself, printing out the stringObj
variable, as shown here:
console.log(typeof stringObj); console.log(stringObj);
What we've done here is we've taken an object, converted it into a JSON string, and printed it onto the
screen. Over in Terminal, I'll navigate into the playground folder using the following command:
cd playground
For now, it doesn't matter where you run the command, but in future it will matter when we are in the
playground folder, so take a